//
//  UserChangeInfoViewController.m
//  TeacherNet
//
//  Created by slz on 2018/1/9.
//  Copyright © 2018年 bnsr. All rights reserved.
//

#import "UserChangeInfoViewController.h"
#import <IQKeyboardManager.h>
#import <TZImagePickerController.h>
#import <PGDatePicker.h>

@interface UserChangeInfoViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,TZImagePickerControllerDelegate,PGDatePickerDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *header;
@property (weak, nonatomic) IBOutlet UILabel *birthdayLabel;
@property (weak, nonatomic) IBOutlet UILabel *sexLabel;
@property (weak, nonatomic) IBOutlet UITextField *profileT;
@property (nonatomic,strong) NSMutableDictionary *params;
@property (weak, nonatomic) IBOutlet UITextField *tureNameT;
@property (weak, nonatomic) IBOutlet UITextField *instrutT;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UITextField *userNameT;
@end

@implementation UserChangeInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _params = [[NSMutableDictionary alloc]init];
    _params[@"id"] = [MFWSdkEnvironment sharedInstance].userInfo.uid;
    _params[@"sex"] = @"1";
    
    
    self.showNavigationBar = YES;
    [self setControllerTitle:@"修改信息"];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"back_icon" selectImage:nil addTarget:self andAction:@selector(backAction)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWIthTitle:@"完成" addTarget:self andAction:@selector(finsihedAction)];

    MFWUserInfo * userInfo = [MFWSdkEnvironment sharedInstance].userInfo;
    [_header sd_setImageWithURL:[NSURL URLWithString:kAPI_IMAGE_HOST(userInfo.logoUrl)] randomPlaceHolder:YES];
    _userNameT.text = userInfo.nickName;
    _tureNameT.text = userInfo.trueName;
    _phoneLabel.text = userInfo.phone;
    _profileT.text = userInfo.uIntro;
    _instrutT.text = userInfo.profile;
    _birthdayLabel.text = userInfo.birthday;
    _sexLabel.text = userInfo.sex;
    _userNameT.delegate = self;
    _tureNameT.delegate = self;
    _profileT.delegate = self;
    _instrutT.delegate = self;
    // Do any additional setup after loading the view from its nib.
}

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
   
    if ([textField isEqual:_userNameT]){
        NSString * userName = textField.text;
        if (userName == nil || userName.length == 0){
            [self.view showTip:@"请输入用户名~"];
            return NO;
        }
        if (userName.length > 30){
            [self.view showTip:@"用户名长度超过30~"];
            return NO;
        }
        _params[@"username"] = userName;
    }else if ([textField isEqual:_tureNameT]){
        NSString * userName = textField.text;
        if (userName == nil || userName.length == 0){
            [self.view showTip:@"请输入您的名字"];
            return NO;
        }
        _params[@"truename"] = userName;
    }else if ([textField isEqual:_profileT]){
        NSString * userName = textField.text;
        _params[@"signature"] = userName;
    }else{
        NSString * userName = textField.text;
        _params[@"profile"] = userName;
    }
    return YES;
}

- (IBAction)birthdayAction:(id)sender {
    [self.view endEditing:YES];
    PGDatePicker * picker = [[PGDatePicker alloc]init];
    picker.delegate = self;
    picker.isHiddenMiddleText = NO;
    picker.datePickerMode = PGDatePickerModeDate;
    picker.datePickerType = PGDatePickerType2;
    
    [picker showWithShadeBackgroud];
}
- (IBAction)actiontwo:(id)sender {
     UIAlertController *actionSheetController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *boy = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _sexLabel.text = @"男";
        _params[@"sex"] = @"1";
    }];
    UIAlertAction *girl = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _sexLabel.text = @"女";
        _params[@"sex"] = @"0";
    }];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [actionSheetController addAction:boy];
    [actionSheetController addAction:girl];
    [actionSheetController addAction:cancle];
    [self presentViewController:actionSheetController animated:YES completion:NULL];
}
- (IBAction)photoAction:(id)sender {
    UIAlertController *actionSheetController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *library = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        imagePickerVc.maxImagesCount = 1;
        imagePickerVc.minImagesCount = 1;
        imagePickerVc.allowPickingVideo = NO;
        imagePickerVc.allowCrop = YES;
        imagePickerVc.photoWidth = 50;
        imagePickerVc.photoPreviewMaxWidth = 50;
        imagePickerVc.allowPickingOriginalPhoto = NO;
        imagePickerVc.cropRect = CGRectMake(0, kScreenHeight/2 - kScreenWidth/2, kScreenWidth, kScreenWidth);
        imagePickerVc.showSelectBtn = NO;
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            if (photos && photos.count >= 1){
                UIImage * image = photos.firstObject;
                image = [self cropImage:image scale:0.5];
                self.header.image = image;
                NSString * base64Image = [self image2DataURL:image];
                [_params setObject:base64Image forKey:@"icon"];
            }
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    }];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
  
    [actionSheetController addAction:library];
    [actionSheetController addAction:cancle];
    [self presentViewController:actionSheetController animated:YES completion:NULL];
}


-(UIImage *)cropImage:(UIImage *)image scale:(CGFloat)scale
{
    CGSize newSize = CGSizeMake(image.size.width *scale, image.size.height *scale);
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


- (BOOL) imageHasAlpha: (UIImage *) image
{
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image.CGImage);
    return (alpha == kCGImageAlphaFirst ||
            alpha == kCGImageAlphaLast ||
            alpha == kCGImageAlphaPremultipliedFirst ||
            alpha == kCGImageAlphaPremultipliedLast);
}
- (NSString *) image2DataURL: (UIImage *) image
{
    NSData *imageData = nil;
    
    if ([self imageHasAlpha: image]) {
        imageData = UIImagePNGRepresentation(image);
    } else {
        imageData = UIImageJPEGRepresentation(image, 1);
    }
    
    return [imageData base64EncodedStringWithOptions:0];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self dismissViewControllerAnimated:YES completion:nil];
}



- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)finsihedAction{
    [self.view endEditing:YES];
    if (_params.count <= 2){
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    [SVProgressHUD showWithStatus:@"正在修改信息..."];
    [BaseHttpTool post:kAPI_REST_USER_INFO params:_params success:^(id responseObj) {
        [SVProgressHUD dismiss];
        MFWJson * json = [MFWJson jsonWithObject:responseObj];
        BOOL flag = [json booleanValueForKey:@"flag"];
        if (flag){
            if (_delegate && [_delegate respondsToSelector:@selector(userDidChangeInfo)]){
                [_delegate userDidChangeInfo];
            }
            UIAlertController *actionSheetController = [UIAlertController alertControllerWithTitle:@"修改成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *boy = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self.navigationController popToRootViewControllerAnimated:YES];
            }];
            [actionSheetController addAction:boy];
            [self presentViewController:actionSheetController animated:YES completion:NULL];
        }else{
            [SVProgressHUD showErrorWithStatus:@"修改失败~"];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];
}



-(void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents
{
    NSString * showString = [NSString stringWithFormat:@"%d-%d-%d",(int)dateComponents.year,(int)dateComponents.month,(int)dateComponents.day];
    _birthdayLabel.text = showString;
    _params[@"birthday"]= showString;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
